package com.chi.controller;

import com.chi.mapper.DepartmentMapper;
import com.chi.mapper.EmployeeMapper;
import com.chi.pojo.Department;
import com.chi.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    DepartmentMapper departmentMapper;
    @GetMapping("/emps/list")
    public String list(Model model){
        Collection<Employee> list = employeeMapper.getEmployeeList();
        model.addAttribute("list",list);
        return "emp/list";
    }

    @GetMapping("/emp/add")
    public String addEmployeeGet(Model model){
        //查出所有部门的信息
        Collection<Department> departments = departmentMapper.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/emp/add")
    public String addEmployeePost(Employee employee){
        employeeMapper.add(employee);
        return "redirect:/emps/list";
    }

    @GetMapping("/emp/update/{id}")
    public String employeeUpdateGet(@PathVariable("id") int id,Model model){
        Employee employee = employeeMapper.getEmployeeById(id);
        model.addAttribute("employee",employee);
        Collection<Department> departments = departmentMapper.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/update";
    }
    @PostMapping("/emp/update")
    public String employeeUpdatePost(Employee employee){
        employeeMapper.add(employee);
        return "redirect:/emps/list";
    }

    @GetMapping("/emp/delete/{id}")
    public String deleteEmployee(@PathVariable("id") int id){
        employeeMapper.deleteEmployeeById(id);
        return "redirect:/emps/list";
    }

}
